package com.wx_shop.api.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.wx_shop.api.comm.ServiceCode;
import com.wx_shop.api.domain.ProPrice;
import com.wx_shop.api.domain.ProProduct;
import com.wx_shop.api.domain.ProPropval;
import com.wx_shop.api.domain.ProShopcart;
import com.wx_shop.api.domain.gen.ProPriceCriteria;
import com.wx_shop.api.domain.gen.ProPropvalCriteria;
import com.wx_shop.api.domain.gen.ProShopcartCriteria;
import com.wx_shop.api.mapper.ProPriceMapper;
import com.wx_shop.api.mapper.ProProductMapper;
import com.wx_shop.api.mapper.ProPropvalMapper;
import com.wx_shop.api.mapper.ProShopcartMapper;
import com.wx_shop.api.service.ShopCartService;
import com.wx_shop.api.util.BeanUtil;
import com.wx_shop.api.util.ProductUtil;
import com.wx_shop.api.vo.BaseRes;
import com.wx_shop.api.vo.ShopcartVo;

@Service
public class ShopCartServiceImpl implements ShopCartService {

	private static final Logger LOG = LoggerFactory.getLogger(ShopCartServiceImpl.class);
	
	@Autowired
	private ProShopcartMapper shopcartMapper;
	
	@Autowired
	private ProPriceMapper proPriceMapper;
	
	@Autowired
	private ProProductMapper productMapper;
	
	@Autowired
	private ProPropvalMapper propvalMapper;
	
	@Override
	public BaseRes<List<ShopcartVo>> cartList(Integer userId) {
		
		List<ProShopcart> carts = shopcartMapper.cartList(userId);
		List<ShopcartVo> pros = BeanUtil.voConvertList(carts, ShopcartVo.class);
		BaseRes<List<ShopcartVo>> res = new BaseRes<List<ShopcartVo>>();
		res.setServiceCode(ServiceCode.SUCCESS);
		res.setData(pros);
		
		return res;
	}

	@Override
	public BaseRes<String> updateCartItem(Integer userId, Integer itemId, Integer val) {
		
		ProShopcart record = new ProShopcart();
		record.setNum(val);
		
		ProShopcartCriteria mProShopcartCriteria = new ProShopcartCriteria();
		mProShopcartCriteria.createCriteria().andUidEqualTo(userId)
		.andIdEqualTo(itemId);
		
		shopcartMapper.updateByExampleSelective(record, mProShopcartCriteria);
		
		BaseRes<String> res = new BaseRes<String>();
		res.setServiceCode(ServiceCode.SUCCESS);
		return res;
	}

	@Override
	public BaseRes<String> delCartItem(Integer userId, Integer itemId) {
		ProShopcartCriteria mProShopcartCriteria = new ProShopcartCriteria();
		mProShopcartCriteria.createCriteria().andUidEqualTo(userId)
		.andIdEqualTo(itemId);
		
		shopcartMapper.deleteByExample(mProShopcartCriteria);
		
		BaseRes<String> res = new BaseRes<String>();
		res.setServiceCode(ServiceCode.SUCCESS);
		return res;
	}

	@Override
	public BaseRes<String> addCartItem(Integer userId, ShopcartVo shopcartVo) {
		
		BaseRes<String> res = new BaseRes<String>();
		/**
		 * 1、先查出商品价格： 商品无属性时，价格在在pro_product中，库存也在当中，
		 * 		：商品有属性时， 价格和库存在pro_price中
		 * 
		 * 加入购物车条件：1 先判断，商品的库存是否充足。
		 */
		
		Integer productId = shopcartVo.getProId();
		String params = shopcartVo.getParams(); // 商品属性
		
		// 查询商品价格
		ProPriceCriteria mProPriceCriteria = new ProPriceCriteria();
		mProPriceCriteria.createCriteria().andProIdEqualTo(productId);
		long proPrices = proPriceMapper.countByExample(mProPriceCriteria);
		
		// 验证数据 params
		/**
		 * 商品用属性定义，但加入购物车时未提交商品属性，返回错误
		 */
		if( proPrices > 0 && StringUtils.isEmpty(params) ) {
			LOG.error("添加购物车，商品属性未传入： userId={},productId={},params={}", userId, productId, params);
			res.setServiceCode(ServiceCode.INVALID_PARAMS);
			return res;
		}
		
		String price = null; // 价格
		Integer num = null;  // 库存
		String paramsTxt = null;
		ProProduct dbProProduct = productMapper.selectByPrimaryKey(productId);
		
		if( StringUtils.isEmpty(params) ) {
			price = dbProProduct.getPrice();
			num = dbProProduct.getNum(); 
		} else {
			
			paramsTxt = "";
			params = ProductUtil.sortSku(params);
			
			ProPriceCriteria pProPriceCriteria = new ProPriceCriteria();
			pProPriceCriteria.createCriteria()
			.andProIdEqualTo(productId)
			.andSkuEqualTo(params);
			List<ProPrice> pros = proPriceMapper.selectByExample(pProPriceCriteria);
			if( pros.size() > 0 ) {
				price = pros.get(0).getPrice();
				num = pros.get(0).getNum();
				
				// 购物车，商品选择属性
				List<Integer> ids = new ArrayList<Integer>();
				String[] ss = params.split(",");
				for( String s: ss ) {
					if( StringUtils.isNotEmpty(s) ) {
						ids.add(Integer.valueOf(s));
					}
				}
				ProPropvalCriteria pProPropvalCriteria = new ProPropvalCriteria();
				pProPropvalCriteria.createCriteria().andIdIn(ids);
				List<ProPropval> proVals = propvalMapper.selectByExample(pProPropvalCriteria);
				for( int i=0; i<proVals.size(); i++ ) {
					ProPropval ppv = proVals.get(i);
					paramsTxt = paramsTxt + ppv.getShowName();
					if( i< proVals.size() -1 ) {
						paramsTxt = paramsTxt + ";";
					}
				}
			}
		}
		
		/**
		 * 验证，商品库存：
		 */
		if( num == null || num < 1 ) {
			LOG.error("商品库存不足： userId={},productId={},params={},price={},num={}", userId, productId, params, price, num);
			res.setServiceCode(ServiceCode.STORE_NOT_ENOUGH);
			return res;
		}
		
		/**
		 * 些商品和属性选择项可能已经添加到购物车了， 如果存在，购买数量 +1
		 */
		ProShopcartCriteria pProShopcartCriteria = new ProShopcartCriteria();
		ProShopcartCriteria.Criteria pCriteria = pProShopcartCriteria.createCriteria();
		pCriteria.andProIdEqualTo(productId);
		if( StringUtils.isNotEmpty(params) ) {
			pCriteria.andParamsEqualTo(params);
		}
		
		ProShopcart mProShopcart = null;
		List<ProShopcart> pscs = shopcartMapper.selectByExample(pProShopcartCriteria);
		if( pscs.size() > 0 ) {
			mProShopcart = pscs.get(0);
			mProShopcart.setNum(mProShopcart.getNum() + 1);
		} else {
			mProShopcart = new ProShopcart();
			mProShopcart.setUid(userId);
			mProShopcart.setProId(productId);
			mProShopcart.setNum(1);
			mProShopcart.setParams(params);
			mProShopcart.setParamsTxt(paramsTxt);
			mProShopcart.setPrice(price);
			mProShopcart.setCreateTime(new Date());
		}
		mProShopcart.setUpdateTime(new Date());
		
		shopcartMapper.insertSelective(mProShopcart);
		res.setServiceCode(ServiceCode.SUCCESS);
		return res;
	}

	public static void main(String[] args ) {
		String[] sortSku = "7,2,112,2".split(",");
		
		Arrays.sort(sortSku, new Comparator<String>() {
			@Override
			public int compare(String o1, String o2) {
				int n1 = Integer.valueOf(o1);
				int n2 = Integer.valueOf(o2);
				if( n1 > n2 ) { return 1; } 
				else if( n1 == n2 ) { return 0; } 
				else { return -1; }
			}
		});
		
		for( String k: sortSku) {
			System.out.println(k);
		}
	}
}
